<template>
  <div class="personEcharts zy-content">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
<!--        <Col span="4">-->
<!--          <div>-->
<!--            <p class="label">{{$t('common.company')}}</p>-->
<!--            <div class="ipt">-->
<!--              <Select v-model="params.orgId" filterable clearable label-in-value :placeholder="$t('fault.CompanySelection')"-->
<!--                      @on-change="handleChange">-->
<!--                <Option v-for="(item, index) of companyList" :value="item.id" :key="index">{{ item.name }}</Option>-->
<!--              </Select>-->
<!--            </div>-->
<!--          </div>-->
<!--        </Col>-->
        <Col span="6">
          <div>
            <p class="label">{{ $t('equipmentscrapped.Location') }}</p>
            <div class="ipt">
              <Cascader :value.sync="params.orgCodes"/>
<!--              <Cascader clearable :data="orgList" v-model="params.orgCode"-->
<!--                        :placeholder="$t('common.PleaseSelect')"-->
<!--                        change-on-select></Cascader>-->
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('fault.RepairPersonnel')}}</p>
            <div class="ipt">
              <Select v-model="params.repairManIds" filterable clearable multiple  :placeholder="$t('fault.RepairPersonnel')">
                <Option v-for="(item, index) of userList" :value="item.id" :key="index" :label="item.realname"></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('展示时间类型')}}</p>
            <div class="ipt">
              <Select v-model="params.type" filterable clearable :placeholder="$t('fault.DisplayByDay')"  @on-change="handleType">
                <Option v-for="(item, index) of typeList" :value="item.id" :key="index" :label="item.name"></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('时间范围')}}</p>
            <div class="ipt">
              <DatePicker type="daterange" :clearable="false" @on-change="handleChangeDate" :value="dateTimeRange"
                          :format="params.type === 1 ? 'yyyy-MM-dd' : 'yyyy-MM-dd'" :placeholder="$t('fault.failure')"></DatePicker>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button class="search-btn" type="primary" @click="getData">{{ $t('common.Query') }}</Button>
              <Button
                  class="reset-btn"
                  @click="reset()"
              >{{ $t('common.reset') }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <div class="wrap">
      <div class="echartsWrap">
        <div class="title">
          <!-- 故障响应时间 -->
          <div><span class="text">{{ $t('fault.ResponseTime') }}</span>{{ companyName ? `（${companyName}）` : '' }}</div>
          <!-- 响应总时间 -->
          <div><span class="circle"></span><span>{{ $t('fault.ResponseTime') }}</span></div>
        </div>
        <div style="height:350px;" id="echart1001"></div>
      </div>

      <div class="echartsWrap">
        <div class="title">
          <!-- 故障次数及维修时长 -->
          <div><span class="text">{{ $t('维修成本') }} </span>{{ companyName ? `（${companyName}）` : '' }}</div>
          <div><span style="background: #1890ff" class="circle"></span>
          <span>{{ $t('工时成本') }}</span><!-- 维修次数 -->
          <span style="background:#40a9ff;" class="circle"></span>
          <span>{{ $t('物料成本') }}</span></div> <!-- 维修时长 -->
        </div>

        <div style="height:350px;" id="echart2001"></div>
      </div>
    </div>
    <div class="wrap">
      <div class="echartsWrap">
        <div class="title">
          <!-- 人员次数及维修时长 -->
          <div><span class="text">{{ $t('fault.Personnel') }}</span>{{ companyName ? `（${companyName}）` : '' }}</div>
             <!-- 维修次数 -->
          <div><span class="circle" style="background: #6b9cfb"></span><span>{{ $t('fault.MaintenanceTimes') }}</span><span
              class="circle circle2 circle_2"></span>
               <!-- 维修总时长 -->
              <span>{{ $t('fault.TotalMaintenance') }}</span></div>
        </div>
        <div style="height:350px;" id="echart3001"></div>
      </div>
      <div class="echartsWrap">
        <div class="title">
           <!-- 维修评分 -->
          <div><span class="text">{{ $t('fault.Scoring') }}</span>{{ companyName ? `（${companyName}）` : '' }}</div>
           <!-- 维修评分 -->
          <div><span class="circle" style="background: #63cdf7"></span><span>{{ $t('fault.Scoring') }}</span></div>
        </div>
        <div style="height:350px;" id="echart1005"></div>
      </div>
    </div>
  </div>
</template>

<script>
import G2 from "@antv/g2";

let echart1Index = 0
let echart2Index = 0
let echart3Index = 0
let echart4Index = 0

import * as echarts from 'echarts';
import moment from "moment";
import recursion from "@/util/recursion";
import Cascader from '@/components/Cascader'


export default {
  name: "personEcharts",
  components: {
    Cascader
  },
  data() {
    return {
      params: {
        orgId: '',
        repairManIds: [],
      },
      companyName: '',
      typeList: [
        { id: 0, name: '按天展示' },
        { id: 1, name: '按月展示' }
      ],
      statusList: [{ id: 1, name: '我是' }],
      companyList: [],
      userList: [],
      dateTimeRange: [this.$moment(new Date()).subtract(7, 'days').format('YYYY-MM-DD'), this.$moment(new Date()).format('YYYY-MM-DD')],
      echart1: null,
      echart2: null,
      echart3: null,
      echart4: null,
      orgList:[]
    };
  },
  mounted() {
    this.getData()
    this.getCompanyList()
    this.getUser()
    this.getOrgList()

    window.onresize = ()=>{
      this.echart1.resize()
      this.echart2.resize()
    }
  },
  methods: {
    getOrgList() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {level:1}
      }).then(res => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'code',
            children: 'children'
          }
          this.orgList = recursion.convertTree(res.data, obj)
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    handleChange(val) {
      this.companyName = val ? val.label : ''
    },
    handleType(val) {
      if (val === 1) {
        this.dateTimeRange = [this.$moment(new Date()).subtract(1, 'year').format('YYYY-MM-DD'), this.$moment(new Date()).format('YYYY-MM-DD')]
      } else {
        this.dateTimeRange = [this.$moment(new Date()).subtract(7, 'days').format('YYYY-MM-DD'), this.$moment(new Date()).format('YYYY-MM-DD')]
      }
    },
    //日期
    handleChangeDate(val) {
      // console.log(val);
      this.dateTimeRange = val
    },
    getCompanyList() {
      this.axios({
        method: 'get',
        url: '/basic/company/getCompanyListByUser',
        params: {}
      }).then(res => {
        if (res.code === 200) {
          this.companyList = res.data
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
    getUser() {
      this.axios({
        method: "get",
        url: "/basic/user/searchUser",
      }).then((res) => {
        if (res.code === 200) {
          this.userList = res.data
        }
      });
    },
    reset(){
      this.params = {
        orgId: '',
        repairManIds: [],
      };
      this.dateTimeRange = [this.$moment(new Date()).subtract(7, 'days').format('YYYY-MM-DD'), this.$moment(new Date()).format('YYYY-MM-DD')];
      this.getData();
    },
    getData() {
      const data = {
        // orgId: this.params.orgId,
        repairManIds: this.params.repairManIds,
        startDate: moment(this.dateTimeRange[0]).format('YYYY-MM-DD'),
        endDate: moment(this.dateTimeRange[1]).format('YYYY-MM-DD'),
        type: this.params.type || 0
      }
      if (this.params.orgCodes && this.params.orgCodes.length){
          data.orgCodes = this.params.orgCodes
      }
      this.getResponseTime(data)
      this.getRepairCount(data)
      this.getPersonCount(data)
    },
    getResponseTime(data) {
      echart1Index++
      const index = echart1Index
      this.axios({
        method: "post",
        url: "/dms/statistical/fixReactTime",
        data,
      }).then((res) => {
        if (res.code === 200) {
          // const list = res.data.map(v => ({
          //   value: v.avgReactTime,
          //   date: (this.params.type === 1 ? v.applyMonth : v.applyDate) + ' '
          // }))
          let list = res.data;
          let names = []
          let values = []
          for (let i=0;i<list.length;i++){
            values.push(list[i].avgReactTime)
            names.push((this.params.type === 1 ? list[i].applyMonth : list[i].applyDate) + ' ')
          }


          // if (this.echart1) {
          //   this.echart1.changeData({names,values})
          // } else {
            this.initChart1({names,values})
          // }
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    getRepairCount(data) {
      echart2Index++
      const index = echart2Index
      this.axios({
        method: "post",
        // url: "/dms/statistical/fixCountAndRepairCostTime",
        url:"/dms/statistical/repairCost",
        data,
      }).then((res) => {
        index
        if (res.code === 200) {
          let data = res.data;
          let list = {materielPrice:[],hourPrice:[],applyDate:[]}
          for (let i=0;i<data.length;i++){
            const {materielPrice,applyDate, applyMonth, hourPrice} = data[i]
            list.materielPrice.push(materielPrice)
            list.hourPrice.push(hourPrice)
            if(this.params.type === 1){
              list.applyDate.push(applyMonth)
            }else{
              list.applyDate.push(applyDate)
            }

          }
          this.initChart2(list, index)
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    getPersonCount(data) {
      echart3Index++
      const index = echart3Index
      this.axios({
        method: "post",
        url: "/dms/statistical/repairCountAndCostTime",
        data,
      }).then((res) => {
        if (res.code === 200) {
          // const list = res.data.map(v => ({ value: v.repairCount, name: v.repairManName, time: v.repairTime }))
          // const list1 = res.data.map(v => ({ value: v.maintenanceScore, name: v.repairManName }))
          const data = res.data;
          let list1 = {names:[],values:[]}
          let list2 = {names:[],values:[],times:[]}
          for (let i=0;i<data.length;i++){
            list1.names.push(data[i].repairManName)
            list1.values.push(data[i].maintenanceScore)

            list2.names.push(data[i].repairManName)
            list2.values.push(data[i].repairCount)
            list2.times.push(data[i].repairTime)
          }

          // if (this.echart3) {
          //   this.echart3.changeData(list)
          // } else {
            this.initChart3(list2)
          // }
          // if (this.echart4) {
          //   this.echart4.changeData(list1)
          // } else {
            this.initChart4(list1)
          // }
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    initChart1({names,values}) {
      if (this.echart1){
        this.echart1.dispose()
      }

      if (!document.getElementById('echart1001')) return;

      this.echart1 = echarts.init(document.getElementById('echart1001'))
      const option = {
        title: {
          show:false
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          show:false
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: names,
            axisTick: {
              show: false,
            },
            axisLine:{
              lineStyle:{
                color:"rgb(222,222,222)",
                width:2
              }
            },
            axisLabel:{
              color:"rgb(91,91,91)",
              interval: 0,
              rotate:45
            },
          }
        ],
        yAxis: [
          {
            name:`${this.$t('时间')}/H`,
            type: 'value',
            axisTick: {
              show: false,
            },
            axisLine:{
              show:false
            },
            axisLabel:{
              color:"rgb(91,91,91)"
            },
            splitLine:{
              show:true  ,
              lineStyle:{
                color:'rgb(243,243,243)',
                width: 2,
                type:"dashed"
              }
            }
          }
        ],
        series: [
          {
            name: '响应时间',
            type: 'line',
            smooth: false,
            lineStyle: {
              width: 2,
              color:'rgba(24,123,219,1)'
            },
            showSymbol: true,
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgb(24,123,219,.8)'
                },
                {
                  offset: 1,
                  color: 'rgba(24,123,219,.3)'
                }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: values
          },
        ]
      };
      this.echart1.setOption(option)
    },
    initChart2(data) {
      if (this.echart2){
        this.echart2.dispose()
      }

      if (!document.getElementById('echart2001')) return;

      this.echart2 = echarts.init(document.getElementById('echart2001'))

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          show:false
        },
        grid: {
          left: '50',
          right: '30',
          bottom:  '10',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: data.applyDate,
            axisTick: {
              show: false,
            },
            axisLine:{
              lineStyle:{
                color:"rgb(222,222,222)",
                width:2
              }
            },
            axisLabel:{
              color:"rgb(91,91,91)",
              interval: 0,
              rotate:45
            },
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisTick: {
              show: false,
            },
            axisLine:{
              show:false
            },
            axisLabel:{
              color:"rgb(91,91,91)"
            },
            splitLine:{
              show:true  ,
              lineStyle:{
                color:'rgb(243,243,243)',
                width: 2,
                type:"dashed"
              }
            }
          }
        ],
        series: [

          {
            name: '物料成本',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            data: data.materielPrice,
            itemStyle:{
              color:"#40a9ff"
            }
          },
          {
            name: '工时成本',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            data: data.hourPrice,
            itemStyle:{
              color:"#1890ff"
            }
          },
        ]
      };

      this.echart2.setOption(option)
    },
    initChart3({names,values,times}) {
      console.log(  names,values,times)

      if (this.echart3){
        this.echart3.dispose()
      }

      if (!document.getElementById('echart3001')) return;

      this.echart3 = echarts.init(document.getElementById('echart3001'))

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          show:false
        },
        grid: {
          left: '50',
          right: '30',
          bottom:  '10',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: names,
            axisTick: {
              show: false,
            },
            axisLine:{
              lineStyle:{
                color:"rgb(222,222,222)",
                width:2
              }
            },
            axisLabel:{
              color:"rgb(91,91,91)",
              interval: 0,
              // rotate:45
            },
          }
        ],
        yAxis: [
          {
            name: `${this.$t('次数')}`,
            type: 'value',
            axisTick: {
              show: false,
            },
            axisLine:{
              show:false
            },
            axisLabel:{
              color:"rgb(91,91,91)"
            },
            splitLine:{
              show:true  ,
              lineStyle:{
                color:'rgb(243,243,243)',
                width: 2,
                type:"dashed"
              }
            },
            interval:1
          },
          {
            name:`${this.$t('时间')}/H`,
            type: 'value',
            axisTick: {
              show: false,
            },
            axisLine:{
              show:false
            },
            axisLabel:{
              color:"rgb(91,91,91)"
            },
            splitLine:{
              show:true  ,
              lineStyle:{
                color:'rgb(243,243,243)',
                width: 2,
                type:"dashed"
              }
            },
            // interval:1
          }
        ],
        series: [

          {
            name: `${this.$t('次数')}`,
            type: 'bar',
            data: values,
            itemStyle:{
              color:"rgb(24,144,255)"
            }
          },
          {
            name:`${this.$t('时间')}/H`,
            type: 'line',
            yAxisIndex: 1,
            data: times
          }
        ]
      };

      this.echart3.setOption(option)
    },
    initChart4({names,values}) {

      if (this.echart4){
        this.echart4.dispose()
      }

      if (!document.getElementById('echart1005')) return;

      this.echart4 = echarts.init(document.getElementById('echart1005'))

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          show:false
        },
        grid: {
          left: '50',
          right: '30',
          bottom:  '10',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: names,
            axisTick: {
              show: false,
            },
            axisLine:{
              lineStyle:{
                color:"rgb(222,222,222)",
                width:2
              }
            },
            axisLabel:{
              color:"rgb(91,91,91)",
              interval: 0,
              // rotate:45
            },
          }
        ],
        yAxis: [
          {
            name:`${this.$t('评分')}`,
            type: 'value',
            axisTick: {
              show: false,
            },
            axisLine:{
              show:false
            },
            axisLabel:{
              color:"rgb(91,91,91)"
            },
            splitLine:{
              show:true  ,
              lineStyle:{
                color:'rgb(243,243,243)',
                width: 2,
                type:"dashed"
              }
            },
            interval:1
          }
        ],
        series: [

          {
            name: `${this.$t('fault.Scoring')}`,
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: values,
            itemStyle:{
              color:"#40a9ff"
            }
          }
        ]
      };

      this.echart4.setOption(option)
    },
  },
};
</script>

<style scoped lang="scss">
.personEcharts {
  .wrap {
    display: flex;
    margin-top: 10px;

    .echartsWrap {
      width: 50%;
      height: 400px;
      background: #fff;
      overflow: hidden;
      border-radius: 10px;

      .title {
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 10px;
        background: #f8f8f8;

        div {
          font-size: 14px;
        }

        .text {
          font-weight: bold;
          font-size: 14px;

          //&:before {
          //  display: inline-block;
          //  vertical-align: middle;
          //  content: "";
          //  width: 10px;
          //  height: 20px;
          //  border-left: 1px dashed #187bdb;
          //  border-right: 1px dashed #187bdb;
          //  margin-right: 10px;
          //  margin-top: -2px;
          //}
        }

        span {
          vertical-align: middle;
        }
      }

      &:first-child {
        margin-right: 10px;
      }

      .circle {
        width: 12px;
        height: 12px;
        background: #187bdb;
        border-radius: 50%;
        display: inline-block;
        margin: 0 5px;
      }

      .circle2 {
        background: green;
        margin: 0 15px;

        &:before {
          display: inline-block;
          content: "";
          width: 8px;
          height: 4px;
          background: green;
          vertical-align: top;
          margin-left: 15px;
          margin-top: 4px;
        }

        &:after {
          display: inline-block;
          content: "";
          width: 8px;
          height: 4px;
          background: green;
          vertical-align: top;
          margin-left: -11px;
          margin-top: -17px;
        }
      }

      .circle_2 {
        background: #5ac9f6;

        &:before {
          background: #5ac9f6;
        }

        &:after {
          background: #5ac9f6;
        }
      }
    }
  }
}
</style>


